import React, { useState, useEffect } from 'react';
import { Card, Form, Button, Select, DatePicker, Table, message, Spin, Alert, Checkbox, Row, Col } from 'antd';
import { ArrowLeftOutlined, CalculatorOutlined, CheckOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import dayjs from 'dayjs';

// 引入API
import { calculateSalary, confirmSalary } from '../../../api/salary';
import { listEmployees } from '../../../api/employee';

const { Option } = Select;

const SalaryCalculate = () => {
    const navigate = useNavigate();
    const [form] = Form.useForm();
    const [loading, setLoading] = useState(false);
    const [calculating, setCalculating] = useState(false);
    const [confirming, setConfirming] = useState(false);
    const [employees, setEmployees] = useState([]);
    const [calculatedSalaries, setCalculatedSalaries] = useState([]);
    const [selectedRowKeys, setSelectedRowKeys] = useState([]);

    useEffect(() => {
        fetchEmployees();
    }, []);

    // 获取员工列表
    const fetchEmployees = async () => {
        try {
            setLoading(true);
            const response = await listEmployees({ pageSize: 1000 }); // 获取所有员工
            setEmployees(response.data || []);
        } catch (error) {
            console.error('获取员工列表失败:', error);
            message.error('获取员工列表失败');
        } finally {
            setLoading(false);
        }
    };

    // 计算薪资
    const handleCalculate = async (values) => {
        try {
            setCalculating(true);
            
            // 准备请求参数
            const params = {
                month: values.month.format('YYYY-MM'),
                employeeIds: values.employeeIds?.length > 0 ? values.employeeIds : undefined
            };
            
            const response = await calculateSalary(params);
            setCalculatedSalaries(response.data || []);
            message.success('薪资计算完成');
        } catch (error) {
            console.error('薪资计算失败:', error);
            message.error('薪资计算失败');
        } finally {
            setCalculating(false);
        }
    };

    // 确认发放薪资
    const handleConfirm = async () => {
        if (selectedRowKeys.length === 0) {
            message.warning('请选择需要确认发放的薪资记录');
            return;
        }

        try {
            setConfirming(true);
            
            const month = form.getFieldValue('month').format('YYYY-MM');
            const params = {
                month,
                salaryIds: selectedRowKeys
            };
            
            await confirmSalary(params);
            message.success('薪资发放确认成功');
            
            // 更新已确认的薪资记录状态
            setCalculatedSalaries(prevSalaries => 
                prevSalaries.map(salary => 
                    selectedRowKeys.includes(salary.id) 
                        ? { ...salary, status: 1 } 
                        : salary
                )
            );
            
            // 清空选择
            setSelectedRowKeys([]);
        } catch (error) {
            console.error('确认发放薪资失败:', error);
            message.error('确认发放薪资失败');
        } finally {
            setConfirming(false);
        }
    };

    // 返回列表
    const handleBack = () => {
        navigate('/salary');
    };

    // 表格行选择配置
    const rowSelection = {
        selectedRowKeys,
        onChange: (selectedRowKeys) => {
            setSelectedRowKeys(selectedRowKeys);
        },
        getCheckboxProps: (record) => ({
            disabled: record.status === 1, // 已发放的不能再次确认
        }),
    };

    // 表格列定义
    const columns = [
        {
            title: 'ID',
            dataIndex: 'id',
            key: 'id',
            width: 80
        },
        {
            title: '员工姓名',
            dataIndex: 'user',
            key: 'user',
            render: (user) => user?.name || '-'
        },
        {
            title: '员工ID',
            dataIndex: 'user',
            key: 'employeeId',
            render: (user) => user?.employeeId || '-'
        },
        {
            title: '部门',
            dataIndex: 'user',
            key: 'department',
            render: (user) => user?.department?.name || '-'
        },
        {
            title: '基本工资',
            dataIndex: 'baseSalary',
            key: 'baseSalary',
            render: (text) => `¥${text ? text.toLocaleString() : 0}`
        },
        {
            title: '绩效奖金',
            dataIndex: 'bonus',
            key: 'bonus',
            render: (text) => `¥${text ? text.toLocaleString() : 0}`
        },
        {
            title: '加班费',
            dataIndex: 'overtime',
            key: 'overtime',
            render: (text) => `¥${text ? text.toLocaleString() : 0}`
        },
        {
            title: '社保',
            dataIndex: 'insurance',
            key: 'insurance',
            render: (text) => `-¥${text ? text.toLocaleString() : 0}`
        },
        {
            title: '个税',
            dataIndex: 'tax',
            key: 'tax',
            render: (text) => `-¥${text ? text.toLocaleString() : 0}`
        },
        {
            title: '实发工资',
            dataIndex: 'netSalary',
            key: 'netSalary',
            render: (text) => `¥${text ? text.toLocaleString() : 0}`
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            render: (status) => (
                <span style={{ color: status === 1 ? '#52c41a' : '#faad14' }}>
                    {status === 1 ? '已发放' : '未发放'}
                </span>
            )
        }
    ];

    return (
        <div className="salary-calculate-container">
            <Card
                title="薪资计算"
                extra={
                    <Button icon={<ArrowLeftOutlined />} onClick={handleBack}>
                        返回
                    </Button>
                }
            >
                <Form
                    form={form}
                    layout="inline"
                    onFinish={handleCalculate}
                    initialValues={{
                        month: dayjs(),
                    }}
                    style={{ marginBottom: 24 }}
                >
                    <Form.Item
                        name="month"
                        label="薪资月份"
                        rules={[{ required: true, message: '请选择薪资月份' }]}
                    >
                        <DatePicker picker="month" style={{ width: 200 }} />
                    </Form.Item>
                    
                    <Form.Item
                        name="employeeIds"
                        label="选择员工"
                    >
                        <Select
                            mode="multiple"
                            placeholder="不选择则计算所有员工"
                            style={{ width: 300 }}
                            loading={loading}
                            allowClear
                            showSearch
                            optionFilterProp="children"
                        >
                            {employees.map(emp => (
                                <Option key={emp.id} value={emp.id}>
                                    {emp.name} ({emp.employeeId || emp.id})
                                </Option>
                            ))}
                        </Select>
                    </Form.Item>
                    
                    <Form.Item>
                        <Button 
                            type="primary" 
                            htmlType="submit" 
                            loading={calculating}
                            icon={<CalculatorOutlined />}
                        >
                            计算薪资
                        </Button>
                    </Form.Item>
                </Form>

                {calculatedSalaries.length > 0 && (
                    <div className="calculated-salaries">
                        <Alert 
                            message="薪资计算完成" 
                            description="以下是计算结果，请检查无误后确认发放。" 
                            type="success" 
                            showIcon 
                            style={{ marginBottom: 16 }}
                        />
                        
                        <div className="table-operations" style={{ marginBottom: 16 }}>
                            <Row justify="space-between" align="middle">
                                <Col>
                                    <span style={{ marginRight: 8 }}>
                                        已选择 {selectedRowKeys.length} 条记录
                                    </span>
                                </Col>
                                <Col>
                                    <Button 
                                        type="primary" 
                                        onClick={handleConfirm} 
                                        loading={confirming}
                                        disabled={selectedRowKeys.length === 0}
                                        icon={<CheckOutlined />}
                                    >
                                        确认发放
                                    </Button>
                                </Col>
                            </Row>
                        </div>
                        
                        <Table 
                            rowSelection={rowSelection}
                            columns={columns}
                            dataSource={calculatedSalaries}
                            rowKey="id"
                            pagination={false}
                            scroll={{ y: 400 }}
                        />
                    </div>
                )}
            </Card>
        </div>
    );
};

export default SalaryCalculate;